//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System.Collections.Generic;

using Mindscape.BackgroundMotion.Core;
using Mindscape.BackgroundMotion.Core.Model;
using Mindscape.BackgroundMotion.Model;

namespace Mindscape.BackgroundMotion.Website.Infrastructure
{
  /// <summary>
  /// Main implementation of the ReferenceDataProvider used in the web site
  /// </summary>
  /// <remarks>
  /// Uses the Repository pattern to load the reference data and then holds it in the current context container
  /// </remarks>
  public class ReferenceDataProvider : IReferenceDataProvider
  {
    public const string ContentTypesKey = "ContentTypes";

    private readonly IContextItems _contextItems;

    /// <summary>
    /// Initializes a new instance of the <see cref="ReferenceDataProvider"/> class.
    /// </summary>
    /// <param name="contextItems">The context items.</param>
    public ReferenceDataProvider(IContextItems contextItems)
    {
      _contextItems = contextItems;
    }

    /// <summary>
    /// The collection of the ContentType instances
    /// </summary>
    /// <value></value>
    public IList<ContentType> ContentTypes
    {
      get
      {
        IList<ContentType> contentTypes 
          = _contextItems.GetItem<IList<ContentType>>(ContentTypesKey);

        if (contentTypes == null)
        {
          using (UnitOfWork.Begin())
          {
            contentTypes = Repository<ContentType>.FindAll();
          }

          _contextItems.SetItem(ContentTypesKey, contentTypes);
        }

        return contentTypes;
      }
    }
  }
}